﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Text;
using log4net;
using System.Reflection;

namespace UPNP.IO
{
	public sealed partial class RootDevice : Device
	{
		public delegate void OnConnectionLostDelegate(object sender, EventArgs e);

		private readonly DeviceSchema _schema;
		private volatile bool _connectionLost = false;
		private readonly object _connectionLostLock = new object();

		public event OnConnectionLostDelegate OnConnectionLost;

		public bool ConnectionLost
		{
			get { return _connectionLost; }
		}

		public DeviceSchema GetSchema()
		{
			return _schema;
		}

		internal void SetConnectionLost()
		{
			if (!_connectionLost)
			{
				lock (_connectionLostLock)
				{
					if (!_connectionLost)
					{
						if (_log.IsDebugEnabled)
							_log.Debug("Setting connection lost for device " + this.UniqueDeviceName);

						try
						{
							// mark
							_connectionLost = true;

							// inform
							if (this.OnConnectionLost != null)
								this.OnConnectionLost(this, EventArgs.Empty);
						}
						catch (Exception e)
						{
							_log.Warn("Failure on setting connection lost", e);
						}
					}
				}
			}
		}

		internal RootDevice(DeviceSchema schema, DeviceDom dom)
            : base(null, dom.RootDevice)
		{
		    Contract.Requires(schema != null);
            Contract.Requires(dom != null);

		    _schema = schema;
		}

	}
}
